import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_yyt/widget/yyt_play_voice_widget.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/util/speak_text_service.dart';
import 'package:ls_work/viewmodel/service_execute/service_execute_list_view_model.dart';
import 'package:ls_work/util/ext_utils.dart';

class ServiceExecuteListFragment extends BaseStatefulMvvmWidget {
  final String? elderCode;
  final String status;
  final String? customerElderId;
  bool canBatch;

  ServiceExecuteListFragment(
      {this.customerElderId,
      this.elderCode,
      required this.status,
      this.canBatch = false});

  @override
  State<StatefulWidget> createState() => _ServiceExecuteListState();
}

class _ServiceExecuteListState extends BaseMvvmListState<
    ServiceExecuteListViewModel, ServiceExecuteListFragment> {
  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Stack(
      children: [
        loadingContentWidget.setLocation(left: 0, top: 0, right: 0, bottom: 0),
        viewModel.showBatchBtn
            ? ElevatedButton(
                    onPressed: () {
                      viewModel.batchSubmit();
                    },
                    style: ButtonStyle(
                        shape: WidgetStateProperty.all(StadiumBorder()),
                        backgroundColor:
                            WidgetStateProperty.all(Colours.app_main)),
                    child: CommonText('提交', textColor: Colors.white))
                .setLocation(left: 16, right: 16, bottom: 16)
            : Container()
      ],
    );
  }

  @override
  EdgeInsets get listPadding => EdgeInsets.only(bottom: 60);

  @override
  Widget createItemWidget(int index) {
    var item = viewModel.listItems[index];
    return item.status == 0
        ? Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CommonText(item.expenseTypeName.isNullOrEmpty()
                  ? item.expenseItem
                  : "【${item.expenseTypeName}】${item.expenseItem}"),
              Container(
                height: 8,
              ),
              CommonText('项目详情：${item.itemDetail ?? ""}', textSize: 15),
              Container(
                height: 8,
              ),
              (item.planTimeFlag != 0)
                  ? Container()
                  : CommonText(
                      "计划时间：${(item.planStartTime ?? "").changeTime()} - ${(item.planEndTime ?? "").changeTime()}",
                      textSize: 14),
              Container(
                height: 8,
              ),
              viewModel.canBatch && item.resultMode == 0
                  ? CheckWithText(
                      title: "",
                      defaultSelected: viewModel.selectItems.contains(item),
                      onChanged: (value) {
                        viewModel.batchClick(item);
                      },
                    ).addToContainer(alignment: Alignment.centerRight)
                  : CommonText('执行', textColor: Colors.white)
                      .addToContainer(
                          decoration: BoxDecoration(
                              color: Colours.app_main,
                              borderRadius: 4.borderRadius),
                          padding:
                              EdgeInsets.symmetric(horizontal: 12, vertical: 6))
                      .onTap(() {
                      SpeakTextService.speak(item.expenseItem??"");
                      viewModel.onExecuteClick(item.id!);
                    }).addToContainer(alignment: Alignment.centerRight)
            ],
          )
            .addToContainer(
                padding: EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 10,
                ),
                color: Colors.white)
            .onTap(() {
            viewModel.batchClick(item);
          })
        : Stack(
            alignment: Alignment.center,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [CommonText(item.expenseItem)],
                  ),
                  Container(
                    height: 8,
                  ),
                  (item.planTimeFlag != 0)
                      ? Container()
                      : CommonText(
                          "计划时间：${(item.planStartTime ?? "").changeTime()} - ${(item.planEndTime ?? "").changeTime()}",
                          textSize: 14),
                  Container(
                    height: 8,
                  ),
                  CommonText('执行人：${item.executor}'),
                  Container(
                    height: 8,
                  ),
                  CommonText('执行时间：${item.finishTime ?? ""}'),
                  Container(
                    height: 8,
                  ),
                  item.resultDesc.isNullOrEmpty()
                      ? Container()
                      : CommonText(item.resultDesc),
                  if (!item.audioId.isNullOrEmpty()) ...[
                    Container(
                      height: 10,
                    ),
                    YYTPlayVoiceWidget("${HttpApi.imageHead}${item.audioId}")
                        .addToContainer(
                            width: 90,
                            decoration: BoxDecoration(
                                color: Colors.green,
                                borderRadius: 10.borderRadius),
                            padding: EdgeInsets.symmetric(
                                horizontal: 0, vertical: 5))
                  ],
                  if (!item.photoIds.isNullOrEmpty()) ...[
                    Container(
                      height: 10,
                    ),
                    GridView.count(
                      crossAxisCount: 3,
                      children: (item.photoIds?.split(RegExp(","))??[]).map((e) {
                        return ImageLoad(
                          "${HttpApi.imageHead}$e",
                          fit: BoxFit.cover,
                        ).onTap(() {
                          var list = item.photoIds?.split(RegExp(","));
                          var index = (list??[]).indexOf(e);
                          showBigImage(
                              context,
                              (list??[])
                                  .map((image) => "${HttpApi.imageHead}$image")
                                  .toList(),
                              position: index);
                        }).toRound(borderRadius: 8.borderRadius);
                      }).toList(),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      mainAxisSpacing: 10,
                      crossAxisSpacing: 10,
                    )
                  ]
                ],
              ),
              item.resultDesc.isNullOrEmpty()
                  ? Icon(
                      Icons.check_circle_outline,
                      color: Colours.app_main,
                    ).setLocation(right: 0)
                  : Container(),
              if (RequestUrlUtils.code == "zhylycs")
                TextButton(
                  onPressed: () {
                    viewModel.sendToFamily();
                  },
                  child: CommonText(
                    '发送至家属',
                    textSize: 14,
                    textColor: Colours.app_main,
                  ),
                  style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(Colors.white),
                      shape: WidgetStateProperty.all(RoundedRectangleBorder(
                          side: BorderSide(color: Colours.app_main, width: 1),
                          borderRadius: 10.borderRadius))),
                ).setLocation(right: 0, top: 0)
            ],
          ).addToContainer(
            width: double.infinity,
            padding: EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 10,
            ),
            color: Colors.white);
  }

  @override
  Widget get separatorDivider => Container(
        height: 10,
      );

  @override
  Widget buildLoadingContentView() {
    return Column(
      children: [
        viewModel.canBatch
            ? Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  CheckWithText(
                      title: viewModel.hasAllChoosed() ? '全不选' : '全选',
                      defaultSelected: viewModel.hasAllChoosed(),
                      onChanged: (checked) {
                        viewModel.allClick(checked);
                      })
                ],
              ).addToContainer(margin: EdgeInsets.symmetric(horizontal: 16))
            : Container(),
        super.buildLoadingContentView()!.setWeight(1)
      ],
    );
  }

  @override
  ServiceExecuteListViewModel createViewModel() {
    return ServiceExecuteListViewModel(context,
        elderCode: widget.elderCode,
        status: widget.status,
        customerElderId: widget.customerElderId,
        canBatch: widget.canBatch);
  }

  @override
  bool get canPullUp => true;
}
